<?php

namespace App\Repositories\Eloquent;

use App\Models\PolicyUpload;
use App\Repositories\Contracts\PolicyUploadInterface;
use App\Services\PolicyUpload\CtripService;
use App\Services\PolicyUpload\QnService;
use App\Services\PolicyUpload\TcService;
use Curl\CurlService\CurlService;
use Curl\StrService\StrService;
use MakeRep\Repository;

class PolicyUploadRepository extends Repository implements PolicyUploadInterface
{

    public $view = 'policyupload';

    public $fillable = ['admin_id','policy_id','policy_code','platform','airline','flight_code','share_flight_code','depart_city_code','arrived_city_code','depart_at','cabin','price','seat','show','status','ext','upload_status','upload_msg'];

    function model()
    {
        return PolicyUpload::class;
    }


    /**
     *
     * @param $param
     * @return mixed
     */
    /**
     *
     * @param $param
     * @return mixed
     */
    public function create($param){

        //平台上传
        if (in_array($param['platform'],$param['admin_platform'])) {

            switch ($param['platform']){

                case 10:
                case 11: {

                    //处理数据
                    CtripService::CtripDataSet($param);

                    $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
                    $uploadRes = $specialPolicyInterface->add([$param]);

                    if ($uploadRes && isset($uploadRes['TradeResult'])){
                        if (isset($uploadRes['TradeResult']['Result']) && isset($uploadRes['TradeResult']['Result']['SuccessList'])) {

                            //成功的话加入政策列表
                            $this->savePolicy($param,$uploadRes['TradeResult']['Result']['SuccessList'][0]);
                            return true;
                        } else {

                            return $uploadRes['TradeResult']['ErrorList'][0]['ErrorMessage'];
                        }

                    } else {

                        return '网络有问题，稍后重试';
                    }

                }

            }
        }

        return '你无权访问，请联系管理员';
    }

    /**
     * 政策详情
     * @param $param
     * @return mixed
     */
    public function policyInfo($param){

        $info = $this->index(['id'=>$param['id'],'admin_id'=>request()->admin['id']]);
        if ($info) {

            $data = [
                $info['policy_id']
            ];

            $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
            if ($info['platform'] == 10) {
                $policyInfo = $specialPolicyInterface->detailSearch($data);
            } else {
                $policyInfo = $specialPolicyInterface->detailMhSearch($data);
            }

            if ($policyInfo && isset($policyInfo['TradeResult']) && isset($policyInfo['TradeResult']['PolicyList'])) {

                $policyInfo['TradeResult']['PolicyList'][0]['platform'] = $info['platform'];
                return $policyInfo['TradeResult']['PolicyList'];
            }

            return '网络有问题，稍后重试';
        }

        return '未找到该条政策';
    }

    /**
     * 政策更新
     * @param $param
     * @return mixed
     */
    public function ajaxUpdate($param){

        //平台上传

        //处理数据
        CtripService::CtripDataSet($param);

        $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');

        switch ($param['platform']){

            case 10:
                $uploadRes = $specialPolicyInterface->change([$param]);
                break;
            case 11:
                $uploadRes = $specialPolicyInterface->changeMh([$param]);
                break;
        }

        if ($uploadRes && isset($uploadRes['TradeResult'])){
            if (isset($uploadRes['TradeResult']['Result']) && isset($uploadRes['TradeResult']['Result']['SuccessList'])) {

                //成功的话加入政策列表
                $this->savePolicy($param,$param['PolicyID']);
                return true;
            } else {

                return $uploadRes['TradeResult']['ErrorList'][0]['ErrorMessage'];
            }

        } else {

            return '网络有问题，稍后重试';
        }
    }

    /**
     * 简易更新政策
     * @param $param
     * @return mixed
     */
    public function itemUpdate($param){

        //平台上传
        $policy = $this->findById($param['id']);
        if ($policy) {

            switch ($policy['platform']){

                case 10:

                    if (!empty($param['status'])) {

                        $param['IsValid'] = $param['status'] == 1 ? 'T' : 'F';
                    }

                    //处理数据
                    $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
                    $uploadRes = $specialPolicyInterface->changePrice([$param]);

                    if ($uploadRes && isset($uploadRes['TradeResult'])){
                        if (isset($uploadRes['TradeResult']['Result']) && isset($uploadRes['TradeResult']['Result']['SuccessList']) && !empty($uploadRes['TradeResult']['Result']['SuccessList'])) {

                            //成功的话加入政策列表
                            $this->updatePolicy($param);
                            return true;
                        } else {

                            return $uploadRes['TradeResult']['ErrorList'][0]['ErrorMessage'];
                        }

                    } else {

                        return '网络有问题，稍后重试';
                    }

                case 11: {

                    if (!empty($param['status'])) {

                        $param['IsValid'] = $param['status'] == 1 ? 'T' : 'F';
                    }

                    //处理数据
                    $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
                    $uploadRes = $specialPolicyInterface->changeMhPrice([$param]);
                    if ($uploadRes && isset($uploadRes['TradeResult'])){
                        if (isset($uploadRes['TradeResult']['Result']) && isset($uploadRes['TradeResult']['Result']['SuccessList']) && !empty($uploadRes['TradeResult']['Result']['SuccessList'])) {

                            //成功的话加入政策列表
                            $this->updatePolicy($param);
                            return true;
                        } else {

                            return $uploadRes['TradeResult']['ErrorList'][0]['ErrorMessage'];
                        }

                    } else {

                        return '网络有问题，稍后重试';
                    }

                    break;
                }
            }
        }

    }

    /**
     * 政策删除
     * @return mixed
     */
    public function deletePolicy($platform,$policyCode,$by='ByCode',$ext = '',$callbackUrl = ''){

        //平台上传
        switch ($platform) {

            case 10:
            {
                $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
                $res = $specialPolicyInterface->delete([$policyCode],$by);
                if ($res && isset($res['TradeResult'])){
                    if (isset($res['TradeResult']['Result']) && (isset($res['TradeResult']['Result']['SuccessList']) || isset($res['TradeResult']['Result']['Summary']['SuccessList']))) {

                        if ($by == 'ByID') {
                            $this->update([['policy_id','=',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                        } else {
                            $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                        }

                        return true;
                    }
                }

                return false;
            }
            case 11: {

                $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
                $res = $specialPolicyInterface->deleteMh([$policyCode],$by);
                if ($res && isset($res['TradeResult'])){
                    if (isset($res['TradeResult']['Result']) && (isset($res['TradeResult']['Result']['SuccessList']) || isset($res['TradeResult']['Result']['Summary']['SuccessList']))) {

                        if ($by == 'ByID') {
                            $this->update([['policy_id','=',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                        } else {
                            $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                        }
                        return true;
                    }
                }

                return false;
            }

            case 20: {

                $rulePolicyPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\CtripRulePolicyInterface');
                $res = $rulePolicyPolicyInterface->delete([$policyCode],$by);

                if ($res && isset($res['TradeResult'])){
                    if (isset($res['TradeResult']['Result']) && (isset($res['TradeResult']['Result']['SuccessList']) || isset($res['TradeResult']['Result']['Summary']['SuccessList']))) {

                        $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                        return true;
                    }
                }


                return false;
            }

            case 21: {

                $rulePolicyPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\CtripRulePolicyInterface');
                $res = $rulePolicyPolicyInterface->deleteMh([$policyCode],$by);

                if ($res && isset($res['TradeResult'])){
                    if (isset($res['TradeResult']['Result']) && (isset($res['TradeResult']['Result']['SuccessList']) || isset($res['TradeResult']['Result']['Summary']['SuccessList']))) {

                        $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                        return true;
                    }
                }


                return false;
            }

            case 30: {
                //去哪删除政策
                $quDelete = [
                    'type'      => 'STOCK',
                    'flights' => [
                        [
                            'type'      => 'STOCK',
                            'policyCode'=> $policyCode.'*'
                        ]
                    ],

                ];

                $quPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
                $res = $quPolicyInterface->delete($quDelete);
                if (substr($res,0,1) == "\n") {
                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }

            case 31:{
                //去哪删除政策
                $quDelete = [
                    'type'      => 'SINGLE',
                    'ext'       => $policyCode,
                    'flights' => [
                        [
                            'type'      => 'SINGLE',
                            'policyCode'=> $policyCode
                        ]
                    ],

                ];

                QnService::QnDataSet($quDelete);

                $quPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
                $res = $quPolicyInterface->delete($quDelete);

                if (substr($res,0,1) == "\n") {

                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }

            case 36:{
                //去哪删除政策
                $quDelete = [
                    'type'      => 'SINGLE',
                    'ext'       => $policyCode,
                    'flights' => [
                        [
                            'type'      => 'SINGLE',
                            'policyCode'=> $policyCode
                        ]
                    ],

                ];

                QnService::QnDataSet($quDelete);

                $quPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
                $res = $quPolicyInterface->fxDelete($quDelete);

                if (substr($res,0,1) == "\n") {

                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }

            case 40:{

                $tcInterface = resolve('App\Repositories\Ota\Tc\Policy\Contracts\TcPolicyInterface');
                $res = $tcInterface->deleteSpecial($policyCode,StrService::uuid(),env('APP_URL').'/api/tc/notify');

                if ($res && isset($res['success']) && $res['isCompress'] === 0) {
                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }
            case 51:
            case 50:{

                $deletePolicy =   [
                    [
                        /* "airline"=> substr($flightCode,0,2),
                         "arrAirport"=> "",
                         "cabinList1"=> "",
                         "cabinList2"=> "",
                         "depAirport"=> "",*/
                        "fuzzyQuery"=> true,
                        "policyCode"=> $policyCode,
                        /*"policySource"=> 0,
                        "saleStartDate"=> "",
                        "salesEndDate"=> "",
                        "status"=> 0,
                        "travelEndDate"=> "",
                        "travelStartDate"=> ""*/
                    ]
                ];

                $res = CurlService::post(env('JAVA_HB_GATEWAY').'/booking/fliggyPolicy/addSpecialPolicy',['deletePolicy'=>$deletePolicy]);

                if (($res && isset($res['code']) && $res['code'] === 0)) {
                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }

            case 52:{

                $deletePolicy =   [
                    [
                        "fuzzyQuery"=> true,
                        "policyCode"=> $policyCode,
                    ]
                ];

                $res = CurlService::post(env('JAVA_HB_GATEWAY').'/booking/fliggyPolicy/addPolicy',['deletePolicy'=>$deletePolicy]);

                if (($res && isset($res['code']) && $res['code'] === 0)) {
                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }

            case 60: {

                $deletePolicy = [
                    "policyCode"    => $policyCode,
                    "type"          => 'PREPAY'
                ];

                $res = CurlService::post(env('JAVA_HB_GATEWAY').'/booking/meiTuanPolicy/add',['deletePolicy'=>[$deletePolicy]]);

                if($res && isset($res['errno']) && $res['errno'] == "5000") {
                    $this->update([['policy_code','like',$policyCode]],['status'=>-1,'deleted_at'=>date('Y-m-d H:i:s')]);
                    return true;
                }

                return false;
            }

        }
    }

    /**
     * 更新本地政策
     * @param $param
     * @return void
     */
    private function updatePolicy($param){

        $data = [
            'status'    => $param['status']
        ];

        $this->update(['id'=>$param['id']],$data);
    }


    /**
     * 保存政策
     * @param $param
     * @param $uploadRes
     * @return void
     */
    private function savePolicy($param,$policyId){

        switch ($param['platform']){
            case 10:
            case 11: {
                $data = [
                    'admin_id'              => $param['admin']['id'],
                    'airline'               => $param['AirLine'],
                    'policy_id'             => $policyId,
                    'policy_code'           => $param['PolicyCode'],
                    'platform'              => $param['platform'],
                    'flight_code'           => $param['RuleDetail'],
                    'depart_city_code'      => $param['DepartPort'],
                    'arrived_city_code'     => $param['ArrivePort'],
                    'depart_at'             => $param['GoEffectDate'],
                    'cabin'                 => $param['SubClass'],
                    'price'                 => $param['PrintPrice'],
                    'seat'                  => $param['TicketInventory'],
                    'status'                => $param['IsValid'] == 'T' ? 1 : 2,
                ];

                break;
            }
        }


        if (empty($param['id'])) {

            $res = $this->add($data);
        } else {
            $res = $this->update(['id'=>$param['id']],$data);
        }

    }
}